package com.hellohu.mbg.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;
import java.util.Properties;

/**
 * 生成Model的toString的相关代码插件
 */
public class GenerateModelToStringPlugin extends PluginAdapter {

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        generateToString(introspectedTable, topLevelClass);
        return super.modelBaseRecordClassGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass,
                                                      IntrospectedTable introspectedTable) {

        generateToString(introspectedTable, topLevelClass);
        return super.modelRecordWithBLOBsClassGenerated(topLevelClass, introspectedTable);
    }

    @Override
    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        generateToString(introspectedTable, topLevelClass);
        return true;
    }

    /**
     * 具体生成toString方法
     *
     * @param introspectedTable table对象
     * @param topLevelClass     model类
     */
    private void generateToString(IntrospectedTable introspectedTable, TopLevelClass topLevelClass) {

        Method toStringMethod = new Method("toString");
        toStringMethod.setVisibility(JavaVisibility.PUBLIC);
        toStringMethod.setReturnType(FullyQualifiedJavaType.getStringInstance());
        toStringMethod.addAnnotation("@Override");
        toStringMethod.addBodyLine("StringBuilder sb = new StringBuilder();");
        toStringMethod.addBodyLine("sb.append(getClass().getSimpleName());");
        toStringMethod.addBodyLine("sb.append(\" [\");");
        StringBuilder sb = new StringBuilder();
        List<Field> fieldList = topLevelClass.getFields();
        for (int i = 0; i < fieldList.size(); ++i) {
            Field field = fieldList.get(i);
            String property = field.getName();
            sb.setLength(0);
            String separator = i == 0 ? " " : " ,";
            sb.append("sb.append(\"").append(separator).append(property).append("=\")").append(".append(")
                    .append(property).append(");");
            toStringMethod.addBodyLine(sb.toString());
        }

        toStringMethod.addBodyLine("sb.append(\"]\");");
        toStringMethod.addBodyLine("return sb.toString();");
        topLevelClass.addMethod(toStringMethod);
    }

    @Override
    public boolean validate(List<String> list) {
        return true;
    }
}
